package demoxsgl_300.com.jj0588;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.display.DisplayManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

import demoxsgl_300.com.jj0588.bean.MyEvent;
import demoxsgl_300.com.jj0588.utils.CheckPermissionsUtil;
import demoxsgl_300.com.jj0588.utils.FileUtil;
import demoxsgl_300.com.jj0588.vie.CameraSurfaceView;


public class Record_DS_Activity extends AppCompatActivity {
    private CameraSurfaceView cameraSurfaceView;

//    int dd;
private ImageView screenShotPic;

    private MediaProjectionManager projectionManager;

    private MediaProjection mediaProjection;

    private ImageReader imageReader;

    String imageName;
    Bitmap bitmap;

    int width;
    int height;
    int dpi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zd);

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);


        CheckPermissionsUtil checkPermissionsUtil = new CheckPermissionsUtil(this);
        checkPermissionsUtil.requestAllPermission(this);
        mHandler.postDelayed(r, 3000);//延时100毫秒
        cameraSurfaceView = (CameraSurfaceView) findViewById(R.id.cameraSurfaceView);



        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;
        height = metric.heightPixels;
        dpi = metric.densityDpi;
        //获取MediaProjectionManager
        projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);






        findViewById(R.id.capture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraSurfaceView.capture();
            }
        });
        ((ToggleButton) findViewById(R.id.record)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cameraSurfaceView.startRecord();
                    iskai = true;
                    //设置录制时长为10秒视频

                } else {
                    cameraSurfaceView.stopRecord();
                    iskai = false;
                    cameraSurfaceView.switchLight(false);
                }

            }
        });
        ((ToggleButton) findViewById(R.id.light)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });
        ((ToggleButton) findViewById(R.id.runBack)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                cameraSurfaceView.setRunBack(isChecked);
            }
        });
        ((ToggleButton) findViewById(R.id.switchCamera)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                cameraSurfaceView.setDefaultCamera(!isChecked);
            }
        });


    }
    Handler mHandler = new Handler();
    private static final int SCREEN_SHOT = 0;
    Runnable r = new Runnable() {

        @Override
        public void run() {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //通过 MediaProjectionManager.createScreenCaptureIntent() 获取 Intent
                startActivityForResult(projectionManager.createScreenCaptureIntent(),SCREEN_SHOT);
            }


            //每隔1s循环执行run方法
            mHandler.postDelayed(this, 1000);
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraSurfaceView.closeCamera();
        mHandler.removeCallbacksAndMessages(null);
    }

    boolean iskai = false;


    /**
     * 保存图片到文件File。
     *
     * @param src     源图片
     * @param file    要保存到的文件
     * @param format  格式
     * @param recycle 是否回收
     * @return true 成功 false 失败
     */
    public static boolean save(Bitmap src, File file, Bitmap.CompressFormat format, boolean recycle) {
        if (isEmptyBitmap(src))
            return false;

        OutputStream os;
        boolean ret = false;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            ret = src.compress(format, 100, os);
            if (recycle && !src.isRecycled())
                src.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }





    /**
     * Bitmap对象是否为空。
     */
    public static boolean isEmptyBitmap(Bitmap src) {
        return src == null || src.getWidth() == 0 || src.getHeight() == 0;
    }





    //处理返回逻辑
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == SCREEN_SHOT){
            if(resultCode == RESULT_OK){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //通过 MediaProjectionManager.getMediaProjection(resultCode,data) 获取 MediaProjection
                    mediaProjection = projectionManager.getMediaProjection(resultCode, data);
                    //创建 ImageReader,构建 VirtualDisplay
                    /**
                     * @param：width/height: 指定生成图像的宽和高
                     * @param: format 是图像的格式，这个格式必须是 ImageFormat或 PixelFormat 中的一个
                     * @param: maxImages 这个参数指的是你想同时在 ImageReader 里获取到的Image对象的个数
                     */
                    imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 1);

                    /**
                     * @param: 前4个分别为VirtualDisplay 的名字，宽，高和dpi。
                     * @param: 第5个参数为DisplayManager 的flag
                     * @param: 第六个参数是一个 Surface。当createVirtualDisplay 调用后，在真实屏幕上的每一帧都会输入到 Surface参数 里。
                     * @param: 第7个参数是一个回调函数，第8个参数是一个Handler
                     */
                    mediaProjection.createVirtualDisplay("ScreenShot", width, height, dpi,
                            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, imageReader.getSurface(), null, null);
                    SystemClock.sleep(100);//这里如果不sleep的话会崩？
                    imageName = System.currentTimeMillis() + ".png";
                    //获取image对象并转化为Bitmap对象
                    Image image = imageReader.acquireNextImage();
                    //这里得到的width, height 是像素格式
                    int width = image.getWidth();
                    int height = image.getHeight();
                    final Image.Plane[] planes = image.getPlanes();
                    //获取 ByteBuffer，里面存放的就是图片的字节流，是字节格式的
                    final ByteBuffer buffer = planes[0].getBuffer();
                    int pixelStride = planes[0].getPixelStride();//两个像素的距离(就是一个像素头部到相邻像素的头部)，字节格式。
                    int rowStride = planes[0].getRowStride();//一行占用的距离(就是一行像素头部到相邻行像素的头部)，这个大小和 width 有关，这里需要注意，因为内存对齐的原因，所以每行会有一些空余。这个值也是字节格式的。
                    int rowPadding = rowStride - pixelStride * width;//用整行的距离减去了一行里像素及空隙占用的距离，剩下的就是空余部分。但是这个是字节格式的
                    //rowPadding需转为像素格式
                    bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                    //创建出合适大小的Bitmap后把Image的buffer传给它就可以得道Bitmap
                    bitmap.copyPixelsFromBuffer(buffer);
                    image.close();

                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), FileUtil.getTime() + " .jpg");

                    try {
                        if (!file.exists())
                            file.createNewFile();

                        boolean ret = save(bitmap, file, Bitmap.CompressFormat.JPEG, true);
                        if (ret) {
                            Toast.makeText(getApplicationContext(), "截图已保持至 " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }
        }
    }





}
